package com.thinkit.cms.service.channel;

import cn.hutool.core.io.FileUtil;
import com.thinkit.cms.api.site.SiteService;
import com.thinkit.core.constant.Channel;
import com.thinkit.processor.channel.BaseChannelAdaptService;
import com.thinkit.utils.enums.ChannelEnum;
import com.thinkit.utils.utils.Checker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;

@Service
public class HomeChannelService extends BaseChannelAdaptService implements Cloneable  {

    @Autowired
    SiteService siteService;

    public void notifyIt(){
        execuate(true);
    }

    public void notifyIt(Boolean notify){
        if(notify){
            execuate(true,true);
        }else{
            execuate(true);
        }
    }

    public void callBack(Object o){
        System.out.println(o);
    }

    @Override
    protected String loadTempPath() {
        return super.tempPath;
    }

    @Override
    protected String loadDestPath() {
        return super.destPath;
    }

    @Override
    protected Map<String, Object> loadTempParams(Map<String,Object> variable) {
        Map<String,Object> params = siteService.findHomePageFile();
        createIndexFile(params);
        setPath(params,false);
        return params;
    }

    private void createIndexFile(Map<String, Object>  map){
        boolean hasKey = map.containsKey(Channel.INDEX_FILE) && map.containsKey(Channel.HREF);
        if(hasKey){
            String indexFile = map.get(Channel.INDEX_FILE).toString(), href =  map.get(Channel.HREF).toString();
            boolean create = Checker.BeNotBlank(indexFile) && Checker.BeNotBlank(href);
            if(create){
                File file = FileUtil.newFile(thinkItProperties.getSitePath()+indexFile);
                String code = "<head><script>var _hmt = _hmt || [];(function() {  var hm = document.createElement(\"script\");  hm.src = \"https://hm.baidu.com/hm.js?c8ff3ece38cb78de846294d90528dcb2\";  var s = document.getElementsByTagName(\"script\")[0];   s.parentNode.insertBefore(hm, s);})();</script></head>\n";
                String content = "<script>window.location.href='"+href+"'</script>";
                FileUtil.writeString(code+content,file, Charset.forName("utf-8"));
            }
        }

    }

    @Override
    public ChannelEnum getName() {
        return ChannelEnum.HOME;
    }
}
